#include <iostream>

using namespace std;

class Solution {
public:
    int myAtoi(string str) {
        int64_t ans = 0;
        bool positive = true;
        bool begin = false;
        for (char& c : str) {
            if (c == ' ' && !begin) {
                continue;
            }
            if (c == '+' || c == '-') {
                if (begin) {
                    break;
                }
                begin = true;
                if (c == '-') {
                    positive = false;
                }
            } else if (c >= '0' && c <= '9') {
                ans = ans * 10 + (c - '0');
                if (ans > -(int64_t) INT32_MIN) {
                    break;
                }
                begin = true;
            } else {
                break;
            }
        }
        if (positive) {
            return min(ans, (int64_t) INT32_MAX);
        }
        return max(-ans, (int64_t) INT32_MIN);
    }
};